<template>
  <div class="login">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <!-- <h3 class="title">超真云生产执行管理系统</h3> -->
      <div style="display: flex;justify-content: center;margin-bottom: 20px;">
        <img src="../assets/images/logo-czy.svg" alt="">
      </div>
      <div class="login-form-tabs">
        <div class="login-form-tabs-box" :class="{'active':!isCode}" @click="isCode=false">
          账号登录
        </div>
        <!-- <div class="login-form-tabs-box" :class="{'active':isCode}" @click="isCode=true">
          钉钉扫码登录
        </div> -->
      </div>
      <div v-show="!isCode">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaOnOff">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 63%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-form-item style="width:100%;">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:100%;background-color: #ff4500;border: none;"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登录</span>
            <span v-else>登录中...</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </div>
      <div v-show="isCode">
        <div id="self_defined_element" class="self-defined-classname"></div>
      </div>
    </el-form>

    <!--  底部  -->
    <div class="el-login-footer">
      <!-- <span @click="toIPC">陕ICP备2022002135号-1</span> -->
    </div>
  </div>
</template>

<script>
import { getCodeImg, getDdauth, ddauth, ddInternalApplication } from "@/api/login";
import { getRouters } from "@/api/menu";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import * as dd from 'dingtalk-jsapi'; // 此方式为整体加载，也可按需进行加载

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "czymes",
        // username: "admin",
        // password: "czymes",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
      isCode: false,
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  mounted() {
    // var info = navigator.userAgent;
    // 通过正则表达式的test方法判断是否包含“Mobile”字符串
    // var isPhone = /mobile/i.test(info);
    if (dd.env.platform !== 'notInDingTalk') {
      let that = this;
      dd.ready(function() {
        dd.runtime.permission.requestAuthCode({
          corpId: "ding919c6a9195e2d227ee0f45d8e4f7c288", // 企业id
          onSuccess: function (info) {
            // authCode  = info.code // 通过该免登授权码可以获取用户身份
            that.$message.success("登陆成功~")
            ddInternalApplication({authCode: info.code}).then(res => {
              if( res.code === 200){
                that.$store.dispatch("setCodeToken", res.token);
                that.$router.push({ path: that.redirect || "/" });
                that.$message.success("登陆成功~");
              }
            })
          }
        });
      });
    }else {
      console.error('钉钉 JS API 未加载');
    }

    const authCode = new URLSearchParams(window.location.search).get('code');
    // 获取参数值
    if(authCode){
      ddauth({authCode}).then(res => {
        if( res.code === 200){
          this.$store.dispatch("setCodeToken", res.token);
          this.$router.push({ path: this.redirect || "/" });
          this.$message.success("登陆成功~");
        }
        console.log(res); 
      })
    }
    // alert(isPhone);
    window.DTFrameLogin(
      {
        id: 'self_defined_element',
        width: 350,
        height: 350,
      },
      {
        redirect_uri: encodeURIComponent('https://mes.czy3d.com/ktg-mes-ui/#/login'), // 登录成功后的回调地址
        // redirect_uri: encodeURIComponent('http://192.168.5.153:82/#/login'), // 登录成功后的回调地址
        client_id: 'dingd0016me0k1klo3tx', // 服务端给你
        scope: 'openid', // 这里一般是openid
        response_type: 'code', 
        prompt: 'consent',
      },
      (loginResult) => {
        const {redirectUrl, authCode, state} = loginResult;
        // 这里可以直接进行重定向
        // 也可以在不跳转页面的情况下，使用code进行授权
        getDdauth(authCode).then(res => {
          // debugger
          if( res.code === 200){
            // window.location.href = redirectUrl;
            this.$store.dispatch("setCodeToken", res.token);
            this.$message.success("登陆成功~");
            this.$router.push({ path: this.redirect || "/" });
            console.log(res);
          }
        })

      },
      (errorMsg) => {
        // debugger
        // 这里一般需要展示登录失败的具体原因
        alert(`Login Error: ${errorMsg}`);
      },
    );
  },
  methods: {
    toIPC(){
      window.open("https://beian.miit.gov.cn/","_blank");
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff;
        if (this.captchaOnOff) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            getRouters().then(res => {
              // console.log(res);
              if(res.code === 200 && res.data){
                const jumpPath = res.data[0].path === '/' ? res.data[0].path : res.data[0].children[0].children ? res.data[0].path + '/' + res.data[0].children[0].path + '/' + res.data[0].children[0].children[0].path : res.data[0].path + '/' + res.data[0].children[0].path;
                // console.log(jumpPath, 'jumpPath');
                this.$router.push({ path: jumpPath || "/" })
              }
            })
            // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
          }).catch(() => {
            this.loading = false;
            if (this.captchaOnOff) {
              this.getCode();
            }
          });
        }
      });
    },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/bg.jpg");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  // background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  font-weight: 600;
  font-size: 26px;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
  &-tabs{
    display: flex;
    margin-bottom: 20px;
    &-box{
      cursor: pointer;
      margin-right: 22px;
      font-size: 18px;
      font-weight: 600;
    }
    .active{
      position: relative;
      &::before{
        content: '';
        position: absolute;
        bottom: -10px;
        left: 0;
        width: 100%;
        height: 6px;
        border-radius: 3px;
        background-color: #ff4500;
      }
    }
  }
  .self-defined-classname{
    // width: 350px;
    // height: 350px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
